global with sharing class AddParticipantToCourseController {
/************************************************************************************************************
	Class Name: 	AddParticipantToCourseController
	Author:			Rafael Alejandro Gatica Patricio
	Class's Goal:	Implement the functions needed for the Visualforce page "AddParticipantToCourse"
************************************************************************************************************/
    
    public String searchText;
    List<User> results;
    Course_participant__c crsPtcpt{get;set;}
    Integer counter = 0;
    String[] listAdd;
    String[] listRemove;
    public String course{get;set;}
    public String dueDate{get;set;}
    
    public AddParticipantToCourseController() {
/************************************************************************************************************
		Class Name: 	AddParticipantToCourseController()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	Class's constructor
************************************************************************************************************/
    	 
    }

    public void setCrsPtcpt(Course_participant__c cp){
/************************************************************************************************************
		Class Name: 	setCrsPtcpt()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	Set crsPtcpt object // 	This object variable is going to be used for create 
											//	Course_participant__c
************************************************************************************************************/
        
        crsPtcpt = cp;
    }

    public Course_participant__c getCrsPtcpt(){
/************************************************************************************************************
		Class Name: 	getCrsPtcpt()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	Get crsPtcpt object
************************************************************************************************************/

        if(crsPtcpt == null) 
            crsPtcpt = new Course_participant__c ();
        return crsPtcpt;
    }
    
    public void setSearchText(String s) {
/************************************************************************************************************
		Class Name: 	setSearchText()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	Set searchText // This variable is going to be used for searching users
************************************************************************************************************/
    	
        searchText = s;
    }
    
    public String getSearchText(){
/************************************************************************************************************
		Class Name: 	getSearchText()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	Get searchText variable
************************************************************************************************************/
        return searchText;
    }
    public List<User> getResults() {

/************************************************************************************************************
		Class Name: 	getResults()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	Get results list
************************************************************************************************************/
        
        return results;
    }


    public PageReference cancel() {
/************************************************************************************************************
		Class Name: 	cancel()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	To go back to Training // a VisualForce Pare
************************************************************************************************************/
        return Page.Training;
    }

    public PageReference doSearch2() {
    	
/************************************************************************************************************
		Class Name: 	doSearch2()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	This method's main goal is to get "result" , from a query where:
							Username matches searchText value.
							ProfileId matches "Custom - Portal Employee"
							And IsActive is "True"
						Also the boolean field "InCourse__c" , will be set as "true" or "false" 
						depending if a Course_participant__c have the same User
************************************************************************************************************/    	
    	
    	Profile prfl = [SELECT 	id, name
    					FROM 	Profile
    					WHERE 	name = 'Custom - Portal Employee'];
       
        results = [ SELECT  Username, ProfileId, Name, Id, IsActive, InCourse__c
                    FROM    User
                    WHERE   Username LIKE :'%'+searchText+'%' 
                    AND     ProfileId =: prfl.Id 
                    AND     IsActive = True];
        
        List<Course_participant__c> searchParticipant = [      SELECT   Id, Course_participant__r.Id, Name, Course_participant__c
                                                               FROM     Course_participant__c
                                                               WHERE    Course__c =: crsPtcpt.Course__c];

        for(User r : results){
                        
            for (Course_participant__c cl : searchParticipant){
                r.InCourse__c = false;
                System.debug('******************************************************For que inicializa los booleanos a cero');
            }
                                
            for (Course_participant__c cl : searchParticipant){
                String temporal = cl.Course_participant__c;
                if(temporal == r.Id){
                        r.InCourse__c = true;
                        System.debug('Se debe ver******************************' + r.Name  + '**************************');
                }
            }
        }
    return null;
        
    }
       
    public PageReference addMembersToCourse() {

/************************************************************************************************************
		Class Name: 	doSearch2()
		Author:			Rafael Alejandro Gatica Patricio
		Class's Goal:	This method's main goal is to get "result" , from a query where:
							Username matches searchText value.
							ProfileId matches "Custom - Portal Employee"
							And IsActive is "True"
						Also the boolean field "InCourse__c" , will be set as "true" or "false" 
						depending if a Course_participant__c have the same User
************************************************************************************************************/    	

    	
        String[] listAddOrg;
        String[] listRemoveOrg;
        if(Apexpages.currentPage().getParameters().get('unitedListAdd').split(',') != null){
             listAddOrg = Apexpages.currentPage().getParameters().get('unitedListAdd').split(',');
        }else {
            listAddOrg=null;
        }
        if(Apexpages.currentPage().getParameters().get('unitedListRemove') != null){
            listRemoveOrg = Apexpages.currentPage().getParameters().get('unitedListRemove').split(',');
        }else{
            listRemoveOrg=null;
        }
        String course = Apexpages.currentPage().getParameters().get('course');
        String dueDate = Apexpages.currentPage().getParameters().get('dueDate');
        
        
        
        System.Debug('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ listAddOrg ' + listAddOrg);
        System.Debug('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ listRemove' + listRemove);

        
        String temp = course;
        Integer counter;
        String[] listAdd = new String[]{};
        String[] listRemove = new String[]{};
        Date dueDte = Date.parse(dueDate);
        
        List<Course_participant__c> tempList=new List<Course_participant__c>();
        List<Course__c> tempCorsPart=[  SELECT  Id, Name
                                        FROM    Course__c
                                        WHERE   Name =: temp
                                        AND     Active__c = true];
        String curso='';
        for(Course__c c : tempCorsPart){
                curso=c.Id;
                System.debug('..............................'+curso);
        }

        for(String l : listAddOrg){
            List<Course_participant__c>tempo= [     SELECT  Course_participant__c, Course__r.Name 
                                                    FROM    Course_participant__c
                                                    WHERE   Course__c =: curso
                                                    AND     Course_participant__c =: l];
            if (tempo.isEmpty()){
                    listAdd.add(l);
            }
            
            System.debug('0000000000000000000     '+l+'     0000000000000000       '+ tempo + '    000000000000      '+listAdd );
        }
        System.debug('++++++++++++++++++++++++++++++++++++++++++++++++++++ Lista Add final' + listAdd);
        try{
            if(tempCorsPart!=null){
                for(Course__c c : tempCorsPart){
                    for (String ide : listAdd){
                        User tempUsr=[SELECT  AccountId 
                                      FROM User
                                      WHERE Id =: ide];
                                            
                        Course_participant__c crsPtcpt = new Course_participant__c();
                        crsPtcpt.Course__c = c.Id;
                        System.debug('----------------------- crsPtcpt.Course__c '+ crsPtcpt.Course__c +' ---------------------------');
                        crsPtcpt.Due_date__c = dueDte;
                        System.debug('----------------------- crsPtcpt.Due_date__c '+ crsPtcpt.Due_date__c +' ---------------------------');
                        crsPtcpt.Course_participant__c = ide;
                        System.debug('----------------------- crsPtcpt.Course_participant__c '+ crsPtcpt.Course_participant__c +' ---------------------------');
                        crsPtcpt.Employee__c = tempUsr.AccountId;
                        System.debug('----------------------- crsPtcpt.Employee__c '+ crsPtcpt.Employee__c +' ---------------------------');
                        tempList.add(crsPtcpt);
                    }
                }
            }
            //ApexPages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, 'Your operation was successful'));
            insert tempList;
        }catch(Exception e){}
        for(String l : listRemoveOrg){
                List<Course_participant__c>tempo= [     SELECT  Course_participant__c, Course__r.Name 
                                                        FROM    Course_participant__c
                                                        WHERE   Course__c =: curso
                                                        AND     Course_participant__c =: l];
                        if (tempo.isEmpty()==false){
                        Delete tempo;
                }
        }
        
        //message = 'Your operation was successful';
    
    return Page.Training;
    }
}